package com.fengmi.security1;

import cn.hutool.json.JSONUtil;
import com.fengmi.entity.SysUser;
import com.fengmi.vo.ResultVO;
import com.util1.JwtUtils;
import com.util1.RsaUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.Collection;

/**
 * @Author 123
 * @Date 2022/2/9 21:02
 * @Version 1.0
 */


public class CustomerBasicAuthenticationFilter extends BasicAuthenticationFilter {


    public CustomerBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1:获取jwt令牌
        String token = request.getHeader("token");

        //放行登录请求'
        String requestURI = request.getRequestURI();
        if ("/u/login".equals(requestURI)) {
            chain.doFilter(request,response);
            return;
        }

        if ("/u/check".equals(requestURI)) {
            chain.doFilter(request,response);
            return;
        }




        if (StringUtils.isEmpty(token)) {
            //不能放行,直接响应客户端
            response(response,new ResultVO(false,"令牌不合法"));
            return;
        }

        //2:解析令牌(非法令牌不能放行)
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa.pub").getPath());
            SysUser sysUser = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);


            //合法令牌

            //3:将用户的主体信息放入security的context中
            Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(sysUser.getRoles()+","+sysUser.getPermissions());


            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(sysUser, null, authorities);


            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


            //放行
            chain.doFilter(request,response);

        } catch (Exception e) {
            e.printStackTrace();


            if(e instanceof JwtParseException ){
                //不能放行
                response(response,new ResultVO(false,"令牌不合法"));
            }else{
                response(response,new ResultVO(false,"系统开小差"));
            }

        }


    }


    private void response(HttpServletResponse response, ResultVO res) {
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter out = response.getWriter();

            out.write(JSONUtil.toJsonStr(res));
            out.flush();
            out.close();
        } catch (Exception e) {

        }
    }
}

